package com.tongzhan.config;

import com.alibaba.fastjson.JSON;
import com.tongzhan.base.Return;
import com.tongzhan.utils.JwtUtil;
import com.tongzhan.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ThreadLocalUtil.clearThreadLocal();
        request.getMethod();
        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtUtil.AUTH_HEADER_KEY);
        if (StringUtils.isBlank(authHeader)) {
            returnJson(response, JSON.toJSONString(new Return(Return.RE_LOGIN, "### 用户未登录，请先登录 ###")));
            return false;
        }
        try {
            //获取token、
            String token;
            if (authHeader.startsWith("Bearer")) {
                token = authHeader.substring(7);
            } else {
                token = authHeader;
            }
            //解析token
            Claims result = JwtUtil.parseJWT(token);
            String subject = result.getSubject();
            ThreadLocalUtil.AdminThreadLocal admin = JSON.parseObject(subject, ThreadLocalUtil.AdminThreadLocal.class);
            if (admin != null) {
                ThreadLocalUtil.AdminThreadLocal local = new ThreadLocalUtil.AdminThreadLocal();
                BeanUtils.copyProperties(admin, local);
                ThreadLocalUtil.putCurrentRequestBasicVO(local);
            }
        } catch (ExpiredJwtException e) {
            returnJson(response, JSON.toJSONString(new Return(Return.RE_LOGIN, "===== Token过期 =====")));
            return false;
        } catch (Exception e) {
            returnJson(response, JSON.toJSONString(new Return(Return.RE_LOGIN, "===== Token解析异常 =====")));
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
